package com.lksoft.bz.command;

import java.util.HashMap;
import java.util.Map.Entry;

import com.lksoft.bz.BeadDB;
import com.lksoft.bz.Bz;
import com.lksoft.bz.StitchPattern;

/**
 * ChangeSize command
 * 
 * @author Lake
 *
 */
public class ChangeSizeCommand implements Command {
	
	// The program
	Bz bz;
		
	// Hash of coordinates -> original color
	HashMap<Integer, Integer> originalColors = new HashMap<>();
	
	// The size change
	private int oldWidth;
	private int oldHeight;
	private int newWidth;
	private int newHeight;

	/**
	 * Constructor
	 * 
	 * @param oldWidth
	 * @param oldHeight
	 * @param newWidth
	 * @param newHeight
	 */
	public ChangeSizeCommand(Bz bz, int oldWidth, int oldHeight, int newWidth, int newHeight){
		this.bz = bz;
		this.oldWidth = oldWidth;
		this.oldHeight = oldHeight;
		this.newWidth = newWidth;
		this.newHeight = newHeight;
	}
	
	@Override
	public void redo() {
		// Save data that will be deleted
		for( int w=newWidth; w<oldWidth; w++ ){
			for( int h=0; h<oldHeight; h++ ){
				int bead = bz.getStitchPanel().getStitchPattern().getBead(w, h);
				if( bead != 0 ){
					originalColors.put(w+h*StitchPattern.MAX_SIZE, bead);
				}
			}
		}
		
		// Clear disappeared cols
		for( int h=newHeight; h<oldHeight; h++ ){
			for( int w=0; w<oldWidth; w++ ){
				int bead = bz.getStitchPanel().getStitchPattern().getBead(w, h);
				if( bead != 0 ){
					originalColors.put(w+h*StitchPattern.MAX_SIZE, bead);
				}
			}
		}
		
		// Set to new size, and delete data
		bz.getStitchPanel().getStitchPattern().setSize(newWidth, newHeight);
		
		bz.getStitchPanel().recalculatePanelSize();
		bz.redraw();
	}

	@Override
	public void undo() {
		// Reset to old size
		bz.getStitchPanel().getStitchPattern().setSize(oldWidth, oldHeight);
		
		// Restore old beads
		boolean usedBeadsChanged = false;
		for( Entry<Integer, Integer> kv : originalColors.entrySet() ){
			int x = kv.getKey() % StitchPattern.MAX_SIZE;
			int y = kv.getKey() / StitchPattern.MAX_SIZE;
			
			usedBeadsChanged |= bz.getStitchPanel().getStitchPattern().setBead(x, y, BeadDB.get().getBeadMap().get(kv.getValue()));
		}
		
		if( usedBeadsChanged ){
			bz.fireUsedBeadsChange();
		}
		bz.getStitchPanel().recalculatePanelSize();
		bz.redraw();
		
		// Clear map
		originalColors.clear();
	}

}
